<template>
  <div class="c-width c-flex c-dis-flex-col com_tree_right_bg c-hidden">
    <el-form class="c-flex c-scroll-y" style="padding: 0 50px;"
       :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules">

      <el-form-item label="考试名称：" prop="name" required>
        <el-input v-model="form.name"/>
      </el-form-item>

      <el-form-item label="考试类型：" prop="examType" required>
        <el-select v-model="form.examType" placeholder="考试类型" style="width: 400px;">
          <el-option
            v-for="dict in dict.type.exam_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="考试时间：" prop="dateRange" >
        <el-date-picker v-model="dateRange" style="width: 400px;"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="试卷：" prop="examPaperName">
        <div class="c-width c-dis-flex-row c-hidden">
          <el-input v-model="form.examPaperName" readOnly/>
          <el-button type="primary" class="link-left" style="margin-left: 20px" size="mini" @click="addQuestion()">
            选择试卷
          </el-button>
        </div>
      </el-form-item>


      <el-form-item label="参与人员：" prop="examUsers">
        <div class="c-width c-dis-flex-row c-hidden">
          <el-input v-model="form.examUsers" readOnly/>
          <el-button type="primary" class="link-left" style="margin-left: 20px" size="mini" @click="openPersonSelect()">
            参与人员
          </el-button>
        </div>

      </el-form-item>

    </el-form>
    <el-col :span="24" class="com_form_btn_center">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="resetForm">重 置</el-button>
    </el-col>
    <!-- 试卷列表 -->
    <el-dialog title="试卷列表" :visible.sync="questionPage.showDialog" width="70%">
      <el-form :model="questionPage.queryParam" ref="queryForm" :inline="true">
        <el-form-item label="试卷名称">
          <el-input v-model="questionPage.queryParam.name" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryForm">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="multipleTable" v-loading="questionPage.listLoading" :data="questionPage.tableData"
                @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="序号" min-width="55px" align="center"> </el-table-column>
        <el-table-column prop="name" label="名称" align="center"  min-width="120px"/>
        <el-table-column label="试卷类型" align="center" prop="paperType" min-width="120px">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.exam_paper_type" :value="scope.row.paperType"/>
          </template>
        </el-table-column>
        <el-table-column prop="suggestTime" label="建议时长(分钟)" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="160px" align="center"/>
      </el-table>

      <pagination v-show="questionPage.total > 0" :total="questionPage.total"
                  :page.sync="questionPage.queryParam.pageNum" :limit.sync="questionPage.queryParam.pageSize"
                  @pagination="search"/>
      <span slot="footer" class="dialog-footer">
          <el-button @click="questionPage.showDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmQuestionSelect">确定</el-button>
     </span>
    </el-dialog>

    <!-- 选择人员 -->
    <personSelect ref="personSelect" @onselected="onselected"></personSelect>
  </div>
</template>

<script>

import { mapGetters, mapState, mapActions } from 'vuex'
import personSelect from "./personSelect";
import Pagination from '@/components/Pagination'
import { PaperEdit, PaperSelect,PaperPageList } from '@/api/examPaper'

import { saveOrEdit,findById ,deptTreeSelect} from '@/api/exam/examManage'

export default {
  components: { Pagination,personSelect },
  dicts: ['exam_paper_type','question_type','exam_type'],
  data() {
    return {
      form: {
        id: null,
        level: null,
        subjectId: null,
        paperType: null,
        limitDateTime: [],
        examType:null,
        name: '',
        suggestTime: null,
        titleItems: [],
        examUsers:null
      },
      // 日期范围
      dateRange: [],
      subjectFilter: null,
      formLoading: false,
      // 部门列表
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      deptExpand: true,
      deptNodeAll: false,
      deptCheckStrictly: true,
      rules: {
        examType: [
          { required: true, message: '请选择考试类型', trigger: 'change' }
        ],
        paperType: [
          { required: true, message: '请选择试卷类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入考试名称', trigger: 'blur' }
        ],
        suggestTime: [
          { required: true, message: '请输入建议时长', trigger: 'blur' }
        ]
      },
      questionPage: {
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          id: null,
          questionType: null,
          subjectId: 1,
          pageNum: 1,
          pageSize: 5
        },
        listLoading: true,
        tableData: [],
        total: 0
      },
      currentTitleItem: null,
      selectedPerson:[]
    }
  },
  created() {
    let id = this.$route.query.id
    let _this = this
    // 获取树结构
    const deptTreeSelect = this.getDeptTree(3)

    if (id && parseInt(id) !== 0) {
      _this.formLoading = true
      findById({ id:id}).then(re => {
        _this.form = re.data;
        //编辑时需要给已选择考试人员进行赋值；
        _this.selectedPerson = _this.form.examUsers.split(",");
        this.dateRange=[re.data.limitStartTime,re.data.limitEndTime];
        //this.form.limitDateTime=[re.data.limitStartTime,re.data.limitEndTime];
        _this.formLoading = false
      })
    }
  },
  methods: {
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(response => {
        this.deptOptions = response.depts
        return response
      })
    },
    submitForm() {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(this.selectedPerson.length==0){
            _this.$modal.msgWarning('请选择参与考试人员');
            return;
          }
          this.formLoading = true
          this.form.limitStartTime = this.dateRange[0];
          this.form.limitEndTime = this.dateRange[1];
          this.form.userIds = this.selectedPerson.map((item => {
            return item.userId
          })).join(",");

          saveOrEdit(this.form).then(re => {
            if (re.code === 200) {
              _this.$modal.msgSuccess(re.msg)
               _this.delCurrentView(_this).then(() => {
                 _this.$router.push('/practice/examination/list')
               })
            } else {
              _this.$modal.msgError(re.message)
              this.formLoading = false
            }
          }).catch(e => {
            this.formLoading = false
          })
        } else {
          return false
        }
      })
    },

    addQuestion(titleItem) {
      this.currentTitleItem = titleItem
      this.questionPage.showDialog = true
      this.search()
    },

    queryForm() {
      this.questionPage.queryParam.pageNum = 1
      this.search()
    },
    confirmQuestionSelect() {
      let _this = this
      if(this.questionPage.multipleSelection.length>0){
        _this.form.examPaperId = this.questionPage.multipleSelection[0].id;
        _this.form.examPaperName = this.questionPage.multipleSelection[0].name;
      }
      /*this.questionPage.multipleSelection.forEach(q => {
        QueSelect(q.id).then(re => {
          _this.currentTitleItem.questionItems.push(re.data)
        })
      })*/
      this.questionPage.showDialog = false
    },

    /**
     * 查询
     */
    search() {
      this.questionPage.listLoading = true
      this.questionPage.queryParam.name='';
      PaperPageList(this.queryParam).then((data) => {
        this.questionPage.tableData = data.rows
        this.questionPage.total = data.total
        this.questionPage.listLoading = false
      })
      .catch(() => {
        this.questionPage.listLoading = false
      })
    },

    handleSelectionChange(rows) {
      if (rows.length > 1) {
        const newRows = rows.filter((it, index) => {
          if (index == rows.length - 1) {
            this.$refs.multipleTable.toggleRowSelection(it, true);
            return true;
          } else {
            this.$refs.multipleTable.toggleRowSelection(it, false);
            return false;
          }
        });
        this.questionPage.multipleSelection = newRows;
      } else {
        this.questionPage.multipleSelection = rows;
      }
    },

    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false
      }
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的部门节点
      //let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      //checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys
    },

    /** 打开选择用户弹窗 */
    openPersonSelect() {
      this.$refs.personSelect.show(this.$route.query.id);
    },

    onselected(obj){
     this.selectedPerson = obj;
     const users = this.selectedPerson.map(x=>{
       return x.nickName
     }).join(",");
     this.form.examUsers = users;
     this.$forceUpdate()
    },

    resetForm() {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        id: null,
        level: null,
        subjectId: null,
        paperType: null,
        limitDateTime: [],
        name: '',
        suggestTime: null,
        titleItems: []
      }
      this.form.id = lastId
    },
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {}
}
</script>

<style lang="scss">
.exampaper-item-box {
  .q-title {
    margin: 0px 5px 0px 5px;
  }

  .q-item-content {
  }
}
</style>
